<script setup>
import { set } from 'vue';
import { forEach, cloneDeep, every, map } from 'lodash-es';
import dayjs from 'dayjs';
import { getToken } from '@/utils/auth';
import { useGlobalState } from '@/store/globalState.js';
import { useRequest } from '@/hooks/requestHooks';
import { useWatch } from '@/hooks/useWatch';
import { getMAInfo, saveMA, getMPInfo } from '@/api/index.js';
import { useFormData } from '../hooks.js';
import { Message } from 'element-ui';
const props = defineProps({
  enterpriseCode: { type: String, default: '' },
  cancel: { type: Boolean, default: null },
  mpciDisabled: { type: Boolean, default: true },
  projectCode: { type: String, default: '' },
  mpciSubmit: { type: Boolean, default: false },
  openTitle: { type: String, default: () => '' },
  mpciBuildingCode: { type: Array, default: () => [] },
});
const emit = defineEmits(['mpciUpload']);
const { enterpriseCode, cancel, mpciDisabled, projectCode, mpciSubmit, openTitle, mpciBuildingCode } = toRefs(props);
const upload = ref(null);
const activeName = ref('');
const agencyList = ref([]);
const REQUIRED = ref(false);
const isShow = ref(false);
const showPDF = ref(false);
const openUrl = ref('');
const tableList = ref([
  {
    energyType: 'WATER', //能源类型
    basisValue: '', //基准值
    guideValue: '', //引导值
    upperLimitValue: '', //上限值
  },
  {
    energyType: 'ELECTRICITY', //能源类型
    basisValue: '', //基准值
    guideValue: '', //引导值
    upperLimitValue: '', //上限值
  },
  {
    energyType: 'AIR', //能源类型
    basisValue: '', //基准值
    guideValue: '', //引导值
    upperLimitValue: '', //上限值
  },
  {
    energyType: 'WARM', //能源类型
    basisValue: '', //基准值
    guideValue: '', //引导值
    upperLimitValue: '', //上限值
  },
]);
const queryParams = ref({
  type: '',
  agreementStartTime: '',
  agreementEndTime: '',
  agreementCode: '',
  basisJson: [],
  projectCode: '',
  operatorName: useGlobalState().globalState.userInfo?.name,
});
const uploadList = ref({
  // 设置上传的请求头部
  headers: { Authorization: 'Bearer ' + getToken() },
  // 上传的地址
  url: useGlobalState().globalState.serverUrl + '/energyservice/monitor/agreement/save',
});
const fileLists = ref([]);
const [infoList, , infoRun] = useRequest(getMPInfo, {
  defaultParams: [{ projectCode: projectCode.value }],
  manual: true,
  onSuccess: async res => {
    let arr = [];
    forEach(res.data?.buildingLevelOneList, n => {
      if (n.level === 1) {
        arr.push(n);
      }
    });
    agencyList.value = arr;
    // activeName.value = res.data?.buildingLevelOneList[0].buildingCode;
    await run({ projectCode: projectCode.value });
  },
});
const [, , run] = useRequest(getMAInfo, {
  defaultParams: [{ projectCode: projectCode.value }],
  manual: true,
  onSuccess: res => {
    const agreement = res.data?.agreement ?? null;
    activeName.value = agencyList.value[0]?.buildingCode ?? '';
    queryParams.value.agreementStartTime = agreement?.agreementStartTime;
    queryParams.value.agreementCode = agreement?.agreementCode ?? '';
    if (agreement?.agreementEndTime?.length > 0) {
      queryParams.value.type = '具体时间';
      queryParams.value.agreementEndTime = agreement.agreementEndTime;
    } else {
      queryParams.value.type = '长期';
    }
    if (agreement?.agreementFileName && agreement?.agreementFile) {
      showPDF.value = true;
      fileLists.value = [
        {
          name: agreement.agreementFileName,
          url: useGlobalState().globalState.fileUrl + agreement.agreementFile,
        },
      ];
    }
    forEach(agencyList.value, n => {
      const arr = [];
      if (res.data?.basis && res.data?.basis?.length > 0) {
        forEach(res.data.basis, el => {
          if (el.buildingCode === n?.buildingCode) {
            arr.push(el);
          }
        });
        n.tableList = arr;
        // set(n.tableList, arr);
      } else {
        n.tableList = cloneDeep(tableList.value);
        // set(n.tableList, tableList.value);
      }
    });
  },
});
const [, , editMARun] = useRequest(saveMA, {
  defaultParams: [],
  manual: true,
  onSuccess: () => {
    Message.success(props.openTitle + '成功');
    emit('mpciUpload', false);
  },
});
const handleAvatarErroe = (err, file, fileList) => {
  Message({
    type: 'error',
    message: err?.msg ?? '上传失败，请重新上传',
  });
  fileLists.value.splice(0, 1);
  upload.value.clearFiles();
  emit('mpciUpload', false);
};
const handleUploadChange = (file, fileList) => {
  fileLists.value = fileList;
};
const handleAvatarSuccess = (response, file, fileList) => {
  if (response.code === 200) {
    Message.success(props.openTitle + '成功');
    emit('mpciUpload', false);
  } else {
    Message({
      type: 'error',
      message: response.msg,
    });
    fileLists.value.splice(0, 1);
    upload.value.clearFiles();
  }
};
const handleRemove = (file, fileList) => {
  fileLists.value = [];
  showPDF.value = false;
};
// 超出限制上传数量回调
const handleExceed = () => {
  Message({
    type: 'warning',
    message: '当前限制最大上传数量：1 ,上传新的文件之前请先删除原文件！',
  });
};
const showInput = computed(() => {
  return openTitle.value === '详情' ? false : true;
});
const addRedStar = (h, { column }) => {
  if (openTitle.value !== '详情') {
    return [h('span', { style: 'color: #F56C6C' }, '*'), h('span', ' ' + column.label)];
  } else {
    return [h('span', ' ' + column.label)];
  }
};
const editInput = (rowIndex, row, id, editItem) => {
  for (let i = 0; i < agencyList.value.length - 1; i++) {
    if (agencyList.value[i].buildingCode === id) {
      // set(agencyList.value[i].tableList[rowIndex], editItem, row[editItem]);
      agencyList.value[i].tableList[rowIndex][editItem] = row[editItem];
    }
  }
};
const convertData = originalData => {
  let arr = [];
  forEach(originalData, n => {
    forEach(n.tableList, el => {
      let obj = {
        ...el,
        buildingCode: n.buildingCode,
      };
      arr.push(obj);
    });
  });
  return JSON.stringify(arr);
};
const handlePreview = () => {
  isShow.value = true;
  openUrl.value = fileLists.value[0]?.url;
};
// 开始时间不能大于结束时间
const pickerOptsStart = ref({
  disabledDate: time => {
    if (queryParams.value.agreementEndTime) {
      return dayjs(time) > dayjs(queryParams.value.agreementEndTime);
    }
  },
});
// 结束时间不能小于开始时间
const pickerOpts = ref({
  disabledDate: time => {
    return dayjs(time) < dayjs(queryParams.value.agreementStartTime);
  },
});
useWatch(
  cancel,
  n => {
    if (n) {
      queryParams.value = {
        type: '',
        agreementStartTime: '',
        agreementEndTime: '',
        agreementCode: '',
        basisJson: [],
        projectCode: '',
        operatorName: useGlobalState().globalState.userInfo?.name,
      };
      fileLists.value = [];
    } else {
      if (projectCode.value.length > 0) infoRun({ projectCode: projectCode.value });
    }
  },
  { deep: true, immediate: true },
);
useWatch(mpciSubmit, n => {
  if (n) {
    if (fileLists.value.length > 0) {
      if (queryParams.value.agreementStartTime && queryParams.value.type) {
        if (
          (queryParams.value.type === '具体时间' && queryParams.value.agreementEndTime) ||
          queryParams.value.type === '长期'
        ) {
          every(agencyList.value, el => {
            every(el.tableList, n => {
              if (n.basisValue && n.guideValue && n.upperLimitValue) {
                if (
                  n.basisValue.toString().length > 0 &&
                  n.guideValue.toString().length > 0 &&
                  n.upperLimitValue.toString().length > 0
                ) {
                  REQUIRED.value = true;
                  return true;
                } else {
                  REQUIRED.value = false;
                  return false;
                }
              } else {
                REQUIRED.value = false;
                return false;
              }
            });
            return REQUIRED.value ? true : false;
          });
        }
        if (!REQUIRED.value) {
          Message.error('表格中的每项为必填');
        } else {
          const arr = cloneDeep(agencyList.value);
          let str = convertData(arr);
          queryParams.value.basisJson = str;
          queryParams.value.projectCode = projectCode.value;
          if (fileLists.value[0].url) {
            let obj = useFormData(queryParams.value);
            editMARun(obj);
          } else {
            upload.value.submit();
          }
        }
      } else {
        Message.error('请选择开始/截止时间！');
      }
    } else {
      Message.error('请上传文件！');
    }
  }
});
// useWatch(
//   openTitle,
//   n => {
//     showPDF.value = n === '编辑' ? true : false;
//   },
//   { immediate: true },
// );
</script>
<template>
  <div style="position: relative">
    <el-form
      :model="queryParams"
      ref="Forms"
      size="small"
      label-width="150px"
      class="u-mt20"
      :disabled="mpciDisabled"
      :inline="true"
    >
      <el-form-item
        label="监测开始时间："
        prop="agreementStartTime"
        :rules="openTitle === '详情' ? [] : { required: true, message: '请选择开始时间', trigger: 'change' }"
      >
        <el-date-picker
          style="width: 300px"
          v-model="queryParams.agreementStartTime"
          type="date"
          :picker-options="pickerOptsStart"
          value-format="yyyy-MM-dd"
          placeholder="请选择开始时间"
        ></el-date-picker>
      </el-form-item>
      <el-form-item
        label="监测截止时间："
        prop="type"
        :rules="{ required: true, message: '请选择时间', trigger: 'change' }"
      >
        <el-select v-model="queryParams.type" class="u-mr10" style="width: 120px">
          <el-option value="具体时间">具体时间</el-option>
          <el-option value="长期">长期</el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        v-show="queryParams.type !== '长期'"
        prop="agreementEndTime"
        :rules="{ required: true, message: '请选择截止时间', trigger: 'change' }"
      >
        <el-date-picker
          style="width: 300px"
          v-model="queryParams.agreementEndTime"
          type="date"
          :picker-options="pickerOpts"
          value-format="yyyy-MM-dd"
          placeholder="请选择截止时间"
        ></el-date-picker>
      </el-form-item>
    </el-form>
    <el-upload
      class="upload-demo u-ml10 u-mt20"
      ref="upload"
      :action="uploadList.url"
      :headers="uploadList.headers"
      accept=".pdf"
      :data="queryParams"
      :on-success="handleAvatarSuccess"
      :on-error="handleAvatarErroe"
      :on-change="handleUploadChange"
      :on-remove="handleRemove"
      multiple
      :file-list="fileLists"
      :auto-upload="false"
      :limit="1"
      :on-exceed="handleExceed"
      :on-preview="handlePreview"
      :disabled="openTitle === '详情' ? true : false"
    >
      <el-button
        size="small"
        plain
        class="el-icon-upload2"
        type="primary"
        style="font-size: 14px"
        :disabled="mpciDisabled"
      >
        点击上传合同附件
      </el-button>
    </el-upload>
    <el-dialog
      title="文件预览"
      top="50px !important"
      :visible="isShow"
      @close="isShow = false"
      width="90%"
      append-to-body
    >
      <iframe :src="openUrl" width="100%" height="800px" style="border: 0">{{ openUrl }}</iframe>
    </el-dialog>
    <el-divider></el-divider>
    <div class="u-fs16 u-reg-text">年度能耗考核指标设置</div>
    <div style="position: relative">
      <el-tabs v-model="activeName" class="u-base-fg">
        <el-tab-pane
          v-for="(item, indexs) in agencyList"
          :key="item?.buildingCode"
          :label="item?.buildingName"
          :name="item?.buildingCode"
        >
          <!-- tableLists[indexs]?.tableData ?? [] -->
          <el-table ref="tables" :key="item?.buildingCode" :data="item?.tableList">
            <el-table-column prop="energyType" label="能源类型">
              <template slot-scope="scope">
                <span v-if="scope.row.energyType === 'ELECTRICITY'">电（kWh）</span>
                <span v-if="scope.row.energyType === 'AIR'">气（m³）</span>
                <span v-if="scope.row.energyType === 'WATER'">水（t）</span>
                <span v-if="scope.row.energyType === 'WARM'">暖（KJ）</span>
              </template>
            </el-table-column>
            <el-table-column prop="basisValue" label="基准值" :render-header="addRedStar">
              <template slot-scope="scope">
                <el-input
                  v-filter-input
                  v-show="showInput"
                  v-model="scope.row.basisValue"
                  clearable
                  size="small"
                  oninput="value=value.replace(/[^0-9.]/g,'')"
                  @blur="editInput(scope.$index, scope.row, item.buildingCode, 'basisValue')"
                />
                <span v-show="!showInput">{{ scope.row.basisValue }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="guideValue" label="引导值" :render-header="addRedStar">
              <template slot-scope="scope">
                <el-input
                  v-filter-input
                  v-show="showInput"
                  v-model="scope.row.guideValue"
                  clearable
                  size="small"
                  oninput="value=value.replace(/[^0-9.]/g,'')"
                  @blur="editInput(scope.$index, scope.row, item.buildingCode, 'guideValue')"
                />
                <span v-show="!showInput">{{ scope.row.guideValue }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="upperLimitValue" label="上限值" :render-header="addRedStar">
              <template slot-scope="scope">
                <el-input
                  v-filter-input
                  v-show="showInput"
                  v-model="scope.row.upperLimitValue"
                  clearable
                  size="small"
                  oninput="value=value.replace(/[^0-9.]/g,'')"
                  @blur="editInput(scope.$index, scope.row, item.buildingCode, 'upperLimitValue')"
                />
                <span v-show="!showInput">{{ scope.row.upperLimitValue }}</span>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>
<style lang="scss" scoped></style>
